package logic

import (
	"context"
	"edu-pro/edurpc/edurpc"
	"edu-pro/pkg"
	"strconv"

	"edu-pro/api/internal/svc"
	"edu-pro/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginWithVerificationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginWithVerificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginWithVerificationLogic {
	return &LoginWithVerificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginWithVerificationLogic) LoginWithVerification(req *types.LoginWithVerificationRequest) (resp *types.Response, err error) {
	//•	手机号 + 验证码登录
	if len(req.Phone) != 11 {
		return &types.Response{
			Message: "您输入的手机号码格式不正确，请重新输入",
			Code:    500,
			Data:    nil,
		}, nil
	}
	data, err := l.svcCtx.EduRpc.UserLoginWithVerification(l.ctx, &edurpc.UserLoginWithVerificationRequest{
		Phone:   req.Phone,
		SmsCode: req.SmsCode,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	handler, err := pkg.TokenHandler(strconv.FormatInt(data.UserId, 10))
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "用户登录成功",
		Code:    200,
		Data:    handler,
	}, nil
}
